'use strict';

/**
 * 递归优化，尾调用
 * @param {any[]} arr
 */
export const tailCall = arr => {
  if (!arr || !arr.length) return;
  if (arr.length === 1) {
    return arr;
  }
};

// 尾调用 示例
export function sortTree(tree, parentId = null) {
  const sortedChildren = [];

  for (const node of tree) {
    if (node.parentId === parentId) {
      const sortedChild = sortTree(tree, node.id); // 尾递归调用
      sortedChildren.push({ ...node, children: sortedChild });
    }
  }

  return sortedChildren.sort((a, b) => a.id - b.id);
}

// 示例数据
export const data = [
  { id: 1, parentId: null },
  { id: 2, parentId: 1 },
  { id: 3, parentId: 1 },
  { id: 4, parentId: 2 },
  { id: 5, parentId: 2 },
  { id: 6, parentId: null },
  { id: 7, parentId: null }
];
